import qs from "query-string";
import axios from "./request.js";
const reqUrl = import.meta.env.VITE_APP_AXIOS_URL;
const imgUrl = import.meta.env.VITE_APP_AXIOS_URL;

function httpImg(url) {
  return `${imgUrl}${url}`;
}

function chUnImg(url) {
  if (url.split(imgUrl).length === 2) {
    return url.split(imgUrl)[1];
  }
  return url;
}

function removePropertyOfNull(obj) {
  const outObj = obj;
  if (obj) {
    Object.keys(obj).forEach((item) => {
      if (typeof obj[item] !== "boolean") {
        if (!obj[item] && obj[item] !== 0) delete outObj[item];
      }
    });
    return outObj;
  }
  return "";
}

function httpGet(url, data, prefix = true) {
  const reqData = qs.stringify(removePropertyOfNull(data));
  const g = reqData ? "?" : "";
  return new Promise((resolve, reject) => {
    axios({
      url: `${prefix ? reqUrl : ""}${url}${g}${reqData}`,
      method: "GET",
      data,
    })
      .then((res) => {
        resolve(res || res);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

function httpPost(url, data) {
  const reqData = JSON.stringify(removePropertyOfNull(data));

  return new Promise((resolve, reject) => {
    axios({
      url: `${reqUrl}${url}`,
      headers: {
        "Content-Type": "application/json",
      },
      method: "POST",
      data: reqData,
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

function httpPostForm(url, data) {
  const formData = new FormData();
  Object.keys(data).forEach((item) => {
    formData.append(item, data[item]);
  });
  // const reqData = JSON.stringify(removePropertyOfNull(data));

  return new Promise((resolve, reject) => {
    axios({
      url: `${reqUrl}${url}`,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      method: "POST",
      data: formData,
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

function httpPut(url, data) {
  const reqData = JSON.stringify(data);
  return new Promise((resolve, reject) => {
    axios({
      url: `${reqUrl}${url}`,
      headers: {
        "Content-Type": "application/json",
      },
      method: "PUT",
      data: reqData,
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

function httpDelete(url) {
  return new Promise((resolve, reject) => {
    axios({
      url: `${reqUrl}${url}`,
      method: "DELETE",
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

export { httpPost, httpPostForm, httpGet, httpDelete, httpPut, httpImg };
